package com.yckj.activechicken.framework.interceptor.impl;

import com.alibaba.fastjson.JSONObject;
import com.yckj.activechicken.common.utils.StringUtils;
import com.yckj.activechicken.common.utils.cache.EhCacheUtils;
import com.yckj.activechicken.common.utils.http.HttpHelper;
import com.yckj.activechicken.framework.interceptor.RepeatSubmitInterceptor;
import com.yckj.activechicken.framework.interceptor.domain.NowData;
import com.yckj.activechicken.framework.repeatable.RepeatedlyRequestWrapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * 判断请求url和数据是否和上一次相同，
 * 如果和上次相同，则是重复提交表单。 有效时间为10秒内。
 *
 * @author zhoujy
 */
@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {
    public final String REPEAT_PARAMS = "repeatParams";

    public final String REPEAT_TIME = "repeatTime";

    public final String CACHE_REPEAT_KEY = "repeatData";

    /**
     * 间隔时间，单位:秒 默认10秒
     * <p>
     * 两次相同参数的请求，如果间隔时间大于该参数，系统不会认定为重复提交的数据
     */
    private int intervalTime = 10;

    public void setIntervalTime(int intervalTime) {
        this.intervalTime = intervalTime;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean isRepeatSubmit(HttpServletRequest request) {
        RepeatedlyRequestWrapper repeatedlyRequest = (RepeatedlyRequestWrapper) request;
        String nowParams = HttpHelper.getBodyString(repeatedlyRequest);

        // body参数为空，获取Parameter的数据
        if (StringUtils.isEmpty(nowParams)) {
            nowParams = JSONObject.toJSONString(request.getParameterMap());
        }

        NowData nowData = new NowData();
        nowData.setRepeatParams(nowParams);
        nowData.setRepeatTime(System.currentTimeMillis());

        // 请求地址（作为存放cache的key值）
        String url = request.getRequestURI();

        NowData sessionData = (NowData)EhCacheUtils.get(url);

        if (sessionData != null) {
            if (compareParams(nowData, sessionData) && compareTime(nowData, sessionData)) {
                return true;
            }
        }

        EhCacheUtils.put(url, nowData, intervalTime, intervalTime);
        return false;
    }

    /**
     * 判断参数是否相同
     */
    private boolean compareParams(NowData nowData, NowData sessionData) {
        String nowParams = nowData.getRepeatParams();
        String preParams = sessionData.getRepeatParams();
        return nowParams.equals(preParams);
    }

    /**
     * 判断两次间隔时间
     */
    private boolean compareTime(NowData nowData, NowData sessionData) {
        long time1 = nowData.getRepeatTime();
        long time2 = sessionData.getRepeatTime();
        if ((time1 - time2) < (this.intervalTime * 1000)) {
            return true;
        }
        return false;
    }
}
